package org.metasketch.ham.project;

import java.io.File;
import java.util.List;

import org.metasketch.editor.IProjectHandler;
import org.metasketch.editor.Project;
import org.metasketch.graphics.Diagram;
import org.metasketch.graphics.DiagramSet;
import org.metasketch.graphics.loader.DiagramFileHandler;
import org.metasketch.ham.model.HAMModel;
import org.metasketch.ham.model.fileloading.HAMModelFileHandler;

public class HAMProjectHandler implements IProjectHandler {

	@Override
	public Project newProject() {

		HAMProject project = new HAMProject();
		// project.setModel(new DEMOModel());
		project.setDirty(true);
		// project.setDiagrams(new DiagramSet());

		return project;
	}

	@Override
	public void saveProject(Project project) throws Throwable {

		HAMProject dproject = (HAMProject) project;

		String path = project.getPath();
		HAMModelFileHandler.write(dproject.getModel(), path);

		File diagramFolder = new File(path + "\\\\ham-diagrams");

		if (!diagramFolder.exists()) {
			diagramFolder.mkdir();
		}

		List<Diagram> diagrams = dproject.getDiagrams().getDiagrams();
		for (Diagram diagram : diagrams) {
			DiagramFileHandler.write(diagram, diagramFolder.getAbsolutePath());
		}

	}

	@Override
	public Project loadProject(String path) throws Throwable {

		HAMProject project = new HAMProject();
		project.setPath(path);

		HAMModel model = HAMModelFileHandler.read(path);
		project.setModel(model);

		File diagramFolder = new File(path + "\\\\ham-diagrams");
		if (!diagramFolder.exists())
			return project;

		DiagramSet set = project.getDiagrams();

		File[] files = diagramFolder.listFiles();
		for (File file : files) {
			if (file.isFile() && file.getName().endsWith(".xml")) {
				Diagram diagram = DiagramFileHandler.read(file
						.getAbsolutePath());
				set.getDiagrams().add(diagram);
			}
		}

		// project.setDiagrams(set);

		return project;

	}
}
